package mango.web.server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;

import org.apache.commons.io.FileUtils;

public class Log {
	public static HashMap<String, Log> logMap = new HashMap<String, Log>();

	public static Log get(String key) {
		Log log = Log.logMap.get(key);
		if (log == null) {
			log = new Log();
			log.file = key;
			log.loadFile();
			Log.logMap.put(key, log);
		}
		return log;
	}

	public String file = "";
	public String string = "";

	public String loadFile() {
		try {
			this.string = FileUtils.readFileToString(new File(this.file));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return this.string;
	}

	public String saveFile() {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(this.file);
			bw = new BufferedWriter(fw);
			bw.write(this.string);
			bw.close();
			fw.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return this.string;
	}

	public String saveFile(String string) {
		this.string = string;
		return this.saveFile();
	}

	public String appendFile(String string) {
		this.string += string + "\n";
		return this.saveFile();
	}
}
